package com.example.netty.netty.TCP粘包拆包问题.解决方案;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class ClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count = 0;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 5; i++) {
            String message = "  hello"+i;
            byte[] content = message.getBytes(CharsetUtil.UTF_8);
            ctx.writeAndFlush(new MessageProtocol(content.length, content));
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol messageProtocol) throws Exception {
        String message = new String(messageProtocol.getContent(), CharsetUtil.UTF_8);
        System.out.println(message+" "+messageProtocol.getLen());
        System.out.println("接收到的长度："+(++count));
    }
}
